package org.spbsu.apco.common.task.impl.matrix;

import org.spbsu.apco.common.Pair;
import org.spbsu.apco.common.data.core.DurationEstimable;
import org.spbsu.apco.common.task.core.BaseTask;

import java.util.ArrayList;
import java.util.List;

/**
 * User: ortemij
 * Date: 07.01.13
 * Time: 14:56
 */
public class RowColumnMultiplicationTask extends BaseTask<Double, Double> implements DurationEstimable<Double> {

    @Override
    public Double execute(final List<Double> inputData) throws Exception {
        final Pair<List<Double>, List<Double>> rowAndColumn = toRowAndColumn(inputData);
        final List<Double> row = rowAndColumn.first;
        final List<Double> column = rowAndColumn.second;
        double sum = 0;
        for (int i = 0; i < row.size(); i++) {
            sum += row.get(i) * column.get(i);
        }
        return sum;
    }

    private static Pair<List<Double>, List<Double>> toRowAndColumn(List<Double> data) {
        List<Double> row = new ArrayList<Double>(data.size() / 2);
        List<Double> column = new ArrayList<Double>(data.size() / 2);
        int i = 0;
        for (double d : data) {
            if (i % 2 == 0) {
                row.add(d);
            } else {
                column.add(d);
            }
            i++;
        }
        return Pair.of(row, column);
    }

    @Override
    public int estimateDuration(List<Double> arguments) {
        return arguments.size();
    }
}
